<template>
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>咨询公告管理</el-breadcrumb-item>
	</el-breadcrumb>

	<el-form :inline="true" :model="queryParams" class="demo-form-inline">
		<el-form-item label="咨询公告名">
			<el-input v-model="queryParams.announcementName" placeholder="请输入咨询公告名" clearable @clear="queryDataList" />
		</el-form-item>
		<el-form-item label="公告内容">
			<el-input v-model="queryParams.announcementContent" placeholder="请输入公告内容" clearable
				@clear="queryDataList" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="queryDataList">搜索</el-button>
			<el-button type="primary" @click="add">新增</el-button>
			<el-button type="danger" @click="batchRemove" :disabled="multipleSelection.length === 0">批量删除</el-button>
		</el-form-item>
	</el-form>

	<el-table :data="dataList" border row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
		<el-table-column type="selection" fixed="left" width="40" />
		<el-table-column property="id" label="ID" fixed="left" width="60" />
		<el-table-column property="announcementName" label="公告名" />
		<el-table-column property="announcementContent" label="公告内容" />
		<el-table-column property="briefImageUrl" label="缩略图">
			<template #default="scope">
				<el-avatar shape="square" size="large" :src="'http://localhost:8080' + scope.row.briefImageUrl" />
			</template>
		</el-table-column>
		<el-table-column property="sendTime" label="发布时间" />
		<el-table-column label="发布人">
			<template #default="scope">
				{{ scope.row.user?.username }}
			</template>
		</el-table-column>
		<el-table-column fixed="right" label="操作" width="160">
			<template #default="scope">
				<el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
				<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>

	<el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
		:page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
		@size-change="handleSizeChange" @current-change="handleCurrentChange" style="margin-top: 20px;" />

	<!-- 新增/编辑弹窗 -->
	<el-dialog :title="title" v-model="dialogFormVisible" width="700px" @close="cancle">
		<el-form :model="formData" label-width="100px">
			<el-form-item label="公告名">
				<el-input v-model="formData.announcementName" placeholder="请输入公告名" />
			</el-form-item>
			<el-form-item label="公告内容">
				<el-input v-model="formData.announcementContent" placeholder="请输入公告内容" type="textarea" rows="4" />
			</el-form-item>

			<el-form-item label="缩略图">
				<el-upload action="http://localhost:8080/upload" list-type="picture-card"
					:on-success="(resp) => handleSuccess(resp, 'brief')" :limit="1"
					:on-preview="handlePictureCardPreview" :file-list="briefImageList"
					:on-remove="() => handleRemove('brief')">
					<el-icon
						style="width: 128px; height: 128px;border: 1px dashed #DCDFE6; border-radius: 5px;font-size: 20px;">
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item>
			<el-form-item label="发布时间" prop="sendTime">
				<el-date-picker v-model="rawSendTime" type="date" placeholder="选择发布时间" :clearable="true"
					@change="formatAndSetSendTime" />
			</el-form-item>
			<el-form-item label="发布人">
				<el-input v-model.number="formData.userId" placeholder="请输入发布人ID" />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取消</el-button>
				<el-button type="primary" @click="confirm">确定</el-button>
			</div>
		</template>
	</el-dialog>

	<!-- 图片预览弹窗 -->
	<el-dialog v-model="dialogVisible" title="图片预览">
		<template #content>
			<img w-full :src="dialogImageUrl" alt="Preview Image" />
		</template>
		<template #footer>
			<el-button @click="dialogVisible = false">关闭</el-button>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
	import { ElMessage, ElMessageBox } from 'element-plus';
	import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
	import { Plus } from '@element-plus/icons-vue';
	import type { UploadUserFile } from 'element-plus';

	// 类型定义
	interface AnnouncementConsult {
		id ?: number;
		announcementName : string;
		announcementContent : string;
		briefImageUrl ?: string;
		sendTime : string;
		userId : number;
		user ?: { username : string };
		del ?: number;
	}

	// 全局 axios
	const { appContext } = getCurrentInstance()!;
	const axios = appContext.config.globalProperties.axios;

	// 查询参数
	const queryParams = reactive({
		announcementName: '',
		announcementContent: '',
		pageNum: 1,
		pageSize: 5,
	});

	// 数据列表
	const total = ref(0);
	const dataList = ref<AnnouncementConsult[]>([]);
	// 批量选择的ID列表
	const multipleSelection = ref<number[]>([]);
	// 对话框标题
	const title = ref('');
	// 表单弹窗显示状态
	const dialogFormVisible = ref(false);
	// 图片预览弹窗显示状态
	const dialogVisible = ref(false);
	// 预览图片URL
	const dialogImageUrl = ref('');
	// 表单数据
	const formData = ref<AnnouncementConsult>({
		announcementName: '',
		announcementContent: '',
		sendTime: '',
		userId: 0,
	});
	// 缩略图上传列表
	const briefImageList = ref<UploadUserFile[]>([]);
	// 日期选择器原始值（临时存储）
	const rawSendTime = ref('');

	// 日期格式化工具函数
	const formatDate = (dateStr : string | undefined) => {
		if (!dateStr) return '';
		const date = new Date(dateStr);
		// 校验日期有效性
		if (isNaN(date.getTime())) {
			ElMessage.error('请选择有效的发布时间');
			return '';
		}
		return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
	};

	// 监听日期选择器变化，格式化后赋值给 formData.sendTime
	const formatAndSetSendTime = () => {
		const formatted = formatDate(rawSendTime.value);
		if (formatted) {
			formData.value.sendTime = formatted;
		} else {
			rawSendTime.value = ''; // 格式化失败，清空选择器
		}
	};

	// 页面加载时查询数据
	onMounted(() => {
		queryDataList();
	});

	// 查询数据列表
	const queryDataList = () => {
		axios.get('/announcementConsult/page', { params: queryParams })
			.then((resp) => {
				if (resp.code === 200) {
					dataList.value = resp.data.list;
					total.value = resp.data.total;
				} else {
					ElMessage.error('查询失败: ' + resp.msg);
				}
			})
			.catch((err) => {
				ElMessage.error('网络错误: ' + err.message);
			});
	};

	// 分页事件
	const handleSizeChange = (size : number) => {
		queryParams.pageSize = size;
		queryDataList();
	};
	const handleCurrentChange = (page : number) => {
		queryParams.pageNum = page;
		queryDataList();
	};

	// 表格多选事件
	const handleSelectionChange = (val : AnnouncementConsult[]) => {
		multipleSelection.value = val.map(item => item.id!);
	};

	// 图片上传成功回调
	const handleSuccess = (resp : any, uploadType : 'brief') => {
		console.log('上传成功:', resp)
		if (resp.code === 200) {
			if (uploadType === 'brief') {
				formData.value.briefImageUrl = resp.data;
				briefImageList.value = [{
					name: resp.data.split('/').pop() || 'brief.jpg',
					url: 'http://localhost:8080' + resp.data
				} as UploadUserFile];
			}
		} else {
			ElMessage.error('上传失败: ' + resp.msg);
		}
	};

	// 图片移除回调
	const handleRemove = (uploadType : 'brief') => {
		if (uploadType === 'brief') {
			formData.value.briefImageUrl = '';
			briefImageList.value = [];
		}
	};

	// 图片预览回调
	const handlePictureCardPreview = (file : UploadUserFile) => {
		dialogImageUrl.value = file.url as string;
		dialogVisible.value = true;
	};

	// 取消操作（重置表单）
	const cancle = () => {
		formData.value = {
			announcementName: '',
			announcementContent: '',
			sendTime: '',
			userId: 0,
		};
		rawSendTime.value = ''; // 重置日期选择器原始值
		briefImageList.value = [];
		dialogFormVisible.value = false;
	};

	// 确认提交（新增/编辑）
	const confirm = () => {
		// 基础校验
		if (!formData.value.announcementName) {
			ElMessage.warning('请输入公告名');
			return;
		}
		if (!formData.value.announcementContent) {
			ElMessage.warning('请输入公告内容');
			return;
		}
		if (!formData.value.userId) {
			ElMessage.warning('请输入发布人ID');
			return;
		}
		if (!formData.value.sendTime) {
			ElMessage.warning('请选择发布时间');
			return;
		}

		// 二次校验日期格式（确保万无一失）
		if (formatDate(formData.value.sendTime) !== formData.value.sendTime) {
			ElMessage.error('发布时间格式错误，请重新选择');
			return;
		}

		if (formData.value.id) {
			axios.put('/announcementConsult', formData.value)
				.then((resp) => {
					if (resp.code === 200) {
						ElMessage.success('编辑成功');
						cancle();
						queryDataList();
					} else {
						ElMessage.error('编辑失败: ' + (resp.msg || '未知错误'));
					}
				})
				.catch((err) => {
					ElMessage.error('网络错误: ' + err.message);
				});
		} else {
			axios.post('/announcementConsult', formData.value)
				.then((resp) => {
					if (resp.code === 200) {
						ElMessage.success('新增成功');
						cancle();
						queryDataList();
					} else {
						ElMessage.error('新增失败: ' + (resp.msg || '未知错误'));
					}
				})
				.catch((err) => {
					ElMessage.error('网络错误: ' + err.message);
				});
		}
	};

	// 打开新增对话框
	const add = () => {
		title.value = '新增公告';
		cancle();
		dialogFormVisible.value = true;
	};

	// 打开编辑对话框
	const edit = (row : AnnouncementConsult) => {
		title.value = '编辑公告';
		formData.value = { ...row };
		// 回显日期选择器原始值（需和后端返回格式兼容）
		rawSendTime.value = row.sendTime;
		formatAndSetSendTime(); // 触发格式化，确保 formData.sendTime 正确

		briefImageList.value = [];
		if (row.briefImageUrl) {
			const url = row.briefImageUrl.startsWith('/')
				? row.briefImageUrl
				: '/' + row.briefImageUrl;

			briefImageList.value = [{
				name: row.briefImageUrl.split('/').pop() || 'brief.jpg',
				url: 'http://localhost:8080' + url
			} as UploadUserFile];
		}

		dialogFormVisible.value = true;
	};

	// 单个删除
	const remove = (id : number) => {
		ElMessageBox.confirm('确定删除该公告吗？', '确认删除', {
			type: 'warning',
		}).then(() => {
			axios.delete(`/announcementConsult/${id}`)
				.then((resp) => {
					if (resp.code === 200) {
						ElMessage.success('删除成功');
						queryDataList();
					} else {
						ElMessage.error(resp.msg || '删除失败');
					}
				})
				.catch((err) => {
					ElMessage.error('网络错误: ' + err.message);
				});
		});
	};

	// 批量删除
	const batchRemove = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请选择要删除的记录');
			return;
		}

		ElMessageBox.confirm(
			`确定删除选中的 ${multipleSelection.value.length} 条记录吗？`,
			'批量删除',
			{
				type: 'warning',
			}
		).then(() => {
			axios.delete('/announcementConsult', {
				params: { ids: multipleSelection.value.join(',') },
			})
				.then((resp) => {
					if (resp.code === 200) {
						ElMessage.success('批量删除成功');
						queryDataList();
					} else {
						ElMessage.error(resp.msg || '批量删除失败');
					}
				})
				.catch((err) => {
					ElMessage.error('网络错误: ' + err.message);
				});
		});
	};
</script>

<style scoped>
	.el-breadcrumb {
		border-bottom: 1px solid #EEEEEE;
		padding: 15px 0;
		margin-bottom: 20px;
	}

	.demo-form-inline {
		padding: 5px 0;
		margin-bottom: 20px;
	}

	.demo-form-inline .el-input,
	.demo-form-inline .el-select {
		width: 175px;
		margin-right: 5px;
	}

	.el-table {
		margin-bottom: 20px;
	}

	.el-pagination {
		text-align: right;
		margin-top: 15px;
	}

	.dialog-footer {
		text-align: right;
	}

	/* 适配textarea高度 */
	.el-textarea {
		width: 100%;
	}
</style>